package com.oceansoft.mobile.biz.api.controller;

import com.alibaba.fastjson.JSONObject;
import com.oceansoft.mobile.common.Constant;
import com.oceansoft.mobile.common.util.HttpClientUtil;
import com.oceansoft.mobile.common.util.Result;
import com.oceansoft.mobile.common.util.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * Created by lenovo on 2017/6/30.
 */
@Controller
@RequestMapping("api/mainPage")
public class ApiStWeixinController {
    @RequestMapping(value = "index", method = RequestMethod.GET)
    public String gotoStIndex(HttpServletRequest request, Model model) {
        String openId = (String) request.getSession().getAttribute("openId");
        if (StringUtils.isEmpty(openId)) {
            openId = request.getParameter("openId");
        }
        request.getSession().setAttribute("openId", openId);
        String source = request.getParameter("source");
        if (StringUtils.isNotBlank(source)) {
            model.addAttribute("source", source);
        }
        return "st_weixin/st_index";
    }
    @ResponseBody
    @RequestMapping(value = "getWeather")
    public String getWeather(HttpServletRequest request) {
        //百度天气API
        String baiduUrl = "http://api.map.baidu.com/telematics/v3/weather?location=北京&output=json&ak=W69oaDTCfuGwzNwmtVvgWfGH";
        StringBuffer strBuf;
        String cityName=request.getParameter("cityName");
        try {
            //通过浏览器直接访问http://api.map.baidu.com/telematics/v3/weather?location=北京&output=json&ak=5slgyqGDENN7Sy7pw29IUvrZ
            //5slgyqGDENN7Sy7pw29IUvrZ 是我自己申请的一个AK(许可码)，如果访问不了，可以自己去申请一个新的ak
            //百度ak申请地址：http://lbsyun.baidu.com/apiconsole/key
            //要访问的地址URL，通过URLEncoder.encode()函数对于中文进行转码
            baiduUrl = "http://api.map.baidu.com/telematics/v3/weather?location="+ URLEncoder.encode(cityName, "utf-8")+"&output=json&ak=BoDHWfB34TUhSDodZSudcbo0";
        } catch (Exception e1) {
            e1.printStackTrace();
        }

        strBuf = new StringBuffer();

        try{
            URL url = new URL(baiduUrl);
            URLConnection conn = url.openConnection();
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));//转码。
            String line = null;
            while ((line = reader.readLine()) != null)
                strBuf.append(line + " ");
            reader.close();
        }catch(Exception e) {
            e.printStackTrace();
        }

        return strBuf.toString();
    }
}
